#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>

static void *thr_job(void *s);

static void thr_exit1(void *s);
static void thr_exit2(void *s);
static void thr_exit3(void *s);

int main(void)
{
    pthread_t tid;
    int err;
    int i = 0;

    err = pthread_create(&tid, NULL, thr_job, NULL);
    if (err) {
        fprintf(stderr, "pthread_create():%s", strerror(err));
        exit(1);
    }

    while (i < 10) {
        write(1, "*", 1);
        sleep(1);
        i ++;
    }
    pthread_cancel(tid);

    // 等待新线程终止
    pthread_join(tid, NULL);

    return 0;
}

// 线程独立执行的函数
static void *thr_job(void *s)
{
    int i;

    // 注册线程终止处理函数
    pthread_cleanup_push(thr_exit1, NULL);
    pthread_cleanup_push(thr_exit2, NULL);
    pthread_cleanup_push(thr_exit3, NULL);

    i = 0;
    while (i < 20) {
        write(1, "!", 1);
        sleep(1);
        i++;
    }

    // sleep(20);

    printf("bye-bye\n");

    // return (void *)0; // 从启动例程返回
    pthread_exit((void *)0);
    // 以下代码不会被执行，因为要与push成对
    pthread_cleanup_pop(0);
    pthread_cleanup_pop(0);
    pthread_cleanup_pop(0);
}

/*
   线程的终止处理程序 
   */
static void thr_exit1(void *s)
{
    printf("%s is called\n", __FUNCTION__);
}

static void thr_exit2(void *s)
{
    printf("%s is called\n", __FUNCTION__);
}

static void thr_exit3(void *s)
{
    printf("%s is called\n", __FUNCTION__);
}


